﻿using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using SpicIE.Common;
using System.Windows.Forms;
using IEAccessibleTabs;
using System.IO;
using SHDocVw;


namespace TabSaver.SaveAsTabs
{
    /// <summary>
    /// This is a simple COM object wich implements the IOleCommandTarget.
    /// The interface is needed when a COM object shall be called via COM object invoke by another component.
    /// There are two needed interface member implementations which can be changed to match the demands of the user
    /// when the plugin is called.
    /// </summary>
    [ComVisible(true),
    ClassInterface(ClassInterfaceType.AutoDual),
    Guid(SaveAsTabsObject.PLUGIN_GUID),
    ProgId(SaveAsTabsObject.PLUGIN_PROGID)]
    public class SaveAsTabsObject : IOleCommandTarget
    {
        [DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();

        public const string PLUGIN_GUID = "456C7EED-9A4C-4c9a-9BD4-CC4815B28333";
        public const string PLUGIN_PROGID = "TabSaver.SaveAsTabs";

        public SaveAsTabsObject()
        {
            // nothing needs to be done here, since this plugin shall only do 
            //something when invoked by another COM object via IOleCommandTarget::Exec
        }

        #region IOLECommandTarget interface implementation
        /// <summary>
        /// interface implementation for communicating with the ole object, in this case the menuitem as com object
        /// </summary>
        /// <param name="pguidCmdGroup"></param>
        /// <param name="cCmds"></param>
        /// <param name="prgCmds"></param>
        /// <param name="pCmdText"></param>
        /// <returns>-1</returns>
        public int QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText)
        {
            return -1;
        }

        /// <summary>
        /// interface implementation for firing the OLE Command event which can be subscribed in the intatiated class
        /// </summary>
        /// <param name="pguidCmdGroup"></param>
        /// <param name="nCmdID"></param>
        /// <param name="nCmdexecopt"></param>
        /// <param name="pvaIn"></param>
        /// <param name="pvaOut"></param>
        /// <returns>-1</returns>
        public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            StreamWriter Tex = null;
            try
            {
                IEAccessible Test = new IEAccessible();

                SaveFileDialog Saver = new SaveFileDialog();
                Saver.Filter = "Tab Files (*.tab)|*.TAB";

                if (Directory.Exists(System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + Path.DirectorySeparatorChar + "IETabs"))
                {
                    Saver.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + Path.DirectorySeparatorChar + "IETabs";
                }
                else
                {

                }


                DialogResult Result = Saver.ShowDialog();
                if (Result == DialogResult.OK)
                {
                    Tex = new StreamWriter(Saver.FileName);

                    foreach (string s in Test.GetTabURLs(GetForegroundWindow()))
                    {
                        Tex.WriteLine(s);
                    }

                    Tex.Flush();

                    System.Collections.IEnumerator windows = new SHDocVw.ShellWindowsClass().GetEnumerator();
                    while (windows.MoveNext())
                    {
                        IWebBrowser2 WebBrowserWindow = (IWebBrowser2)windows.Current;
                        if (WebBrowserWindow.HWND == GetForegroundWindow().ToInt32())
                        {
                            WebBrowserWindow.StatusText = "Tabs Saved";
                            break;
                        }
                    }

                    MessageBox.Show("Tabs Saved", "Tabs Saved", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                }
                else
                {
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
            }
            finally
            {
                if (Tex != null)
                {
                    Tex.Close();
                }
            }

            return -1;
        }
        #endregion
    }
}